/**
 * Created with IntelliJ IDEA.
 * Description:多线程在处理大量数据运算时,效率高于单线程的串发执行
 * User: lenovo
 * Date: 2022-09-04
 * Time: 16:52
 */
public class Demo6 {
    //100亿
    public static final long COUNT = 100_0000_0000L;//默认是integer类型,所以要加L
    public static void main(String[] args) {

        concurrency();
        sarial();

    }
    //串行
    public static void sarial(){
        // 记录 ms 级别的时间戳.
        long startTime = System.currentTimeMillis();
        long a = 0;
        for (long i = 0; i < COUNT; i++) {
            a++;
        }
        a = 0;
        for (long i = 0; i < COUNT; i++) {
            a++;
        }
        long endTime = System.currentTimeMillis();
        System.out.println("串行执行时间:"+(endTime-startTime)+"ms" );
    }
//并发执行

    /**
     * t1,t2,main三个线程,并发执行,宏观上的同时执行
     */
    public static void concurrency(){
        long startTime = System.currentTimeMillis();
        Thread t1 = new Thread(()->{}){
            @Override
            public void run() {
                long a = 0;
                for (long i = 0; i < COUNT; i++) {
                    a++;
                }
            }
        };
        Thread t2 = new Thread(()->{}){
            @Override
            public void run() {
                long a = 0;
                for (long i = 0; i < COUNT; i++) {
                    a++;
                }
            }
        };

        t1.start();
        t2.start();
        //t1.join main线程先阻塞,等到t1执行完了,main在执行
        //t2.join main线程先阻塞,等到t2执行完了,main在执行
        try {
            t1.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        try {
            t2.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        long endTime = System.currentTimeMillis();
        System.out.println("并发执行时间:"+(endTime-startTime)+"ms" );
    }
}
